package com.seeqool.v1;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;


public class MainWindow extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	private static StatusBar statusBar;
	private static JTextArea logBox;
	private static boolean logBoxFilled;
	private static JTabbedPane resultPane;
	private static JPanel runningQueries;
	private static JTextField queryEditor;
	public static QueryManager dbQueryManager;
	
	public MainWindow() {
		// initialize
		super("SeeQooL v1.0");
		setLayout(new BorderLayout());
		Rectangle bounds = getDesktopBounds(); 
		setSize(bounds.width*4/5, bounds.height*4/5);
		setLocation(bounds.width/10, bounds.height/10);
		
		// add Status Bar
		statusBar = new StatusBar();
		setStatus("disconnected");
		getContentPane().add(statusBar, BorderLayout.SOUTH);
		
		// add Tool Bar
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		toolBar.setRollover(true);
		toolBar.add(new IconButton("new.png",  "New project",  this, "New" ));
		toolBar.add(new IconButton("open.png", "Open project", this, "Open"));
		toolBar.add(new IconButton("save.png", "Save project", this, "Save"));
		toolBar.addSeparator();
		toolBar.add(new JLabel("Query: "));
		queryEditor = new JTextField();
		queryEditor.setText("SELECT top 10  id as C_Index, a as S_Trace_1, b as S_Trace_2, c as S_Trace_3 FROM test");
		queryEditor.setText("SELECT id as C, a as S, b as S, c as S FROM test LIMIT 10");
		queryEditor.addActionListener(this);
		queryEditor.setActionCommand("Run");
		toolBar.add(queryEditor);
		toolBar.add(new IconButton("go.png",   "Run query", this, "Run" ));
		toolBar.addSeparator();
		toolBar.add(new IconButton("help.png", "Help",      this, "Help"));
		
		getContentPane().add(toolBar, BorderLayout.PAGE_START);
		
		JTabbedPane leftTabs = new JTabbedPane();
		resultPane = new JTabbedPane();
		JTabbedPane bottomTabs = new JTabbedPane();
		JSplitPane verticalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                                  true,
                                                  new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
                		                                         true,
                		                                         leftTabs, 
                		                                         resultPane), 
                                                  bottomTabs);
		verticalSplit.setResizeWeight(1);
		getContentPane().add(verticalSplit, 
				             BorderLayout.CENTER);
		
		leftTabs.setMinimumSize(new Dimension(150,200));
		leftTabs.add("Database", new DatabaseBrowser());
		leftTabs.add("Queries",  new JLabel("disconnected"));
		
		logBox = new JTextArea();
		logBox.setLineWrap(false);
		logBox.setEditable(false);
		logBoxFilled = false;
		
		runningQueries = new JPanel();
		runningQueries.setLayout(new BoxLayout(runningQueries, BoxLayout.PAGE_AXIS));
		
		bottomTabs.setPreferredSize(new Dimension(300,100));
		bottomTabs.add("Running Queries", new JScrollPane(runningQueries));
		bottomTabs.add("Log",             new JScrollPane(logBox));
		bottomTabs.add("About",  new JLabel("disconnected"));
		
		// display
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Toolkit.getDefaultToolkit().setDynamicLayout(true);
	}
	
	public static void setStatus(String status) {
		statusBar.setText(status);
	}
	
	public static synchronized void addLog(String log) {
		if (logBoxFilled)
			logBox.append(System.getProperty("line.separator"));
		logBox.append("["+(new SimpleDateFormat("HH:mm:ss")).format(new Date())+"] "+log);
		logBoxFilled = true;
	}
	
	public static void addResultPanel(JComponent resultPanel) {
		resultPane.add("Untitled", resultPanel);
		resultPane.setSelectedComponent(resultPanel);
	}
	
	public static void addQuery(JComponent query) {
		runningQueries.add(query);
		runningQueries.updateUI();
	}

	private static Rectangle getDesktopBounds() {
	    try {
	        Point mousePoint = MouseInfo.getPointerInfo().getLocation();
	        GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
	        for (GraphicsDevice device : devices) {
	            Rectangle bounds = device.getDefaultConfiguration().getBounds();
	            if (mousePoint.x >= bounds.x && mousePoint.y >= bounds.y
	                && mousePoint.x <= (bounds.x + bounds.width)
	                && mousePoint.y <= (bounds.y + bounds.height)) {
	            	return bounds;
	            }
	        }
	    } catch (Exception e) {	       
	    }
	    return new Rectangle(0,0,1024,768);
	}
	
	private static String actions = "New OpenSaveRun Help";

	public void actionPerformed(ActionEvent e) {
		int action = actions.indexOf(e.getActionCommand()) / 4;
		switch (action) {
			case 0:
				System.out.println("New");
				break;
			case 1:
				System.out.println("Open");
				break;
			case 2:
				System.out.println("Save");
				break;
			case 3:
				try {
					MainWindow.addQuery(new DBquery(dbQueryManager, queryEditor.getText()));
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				break;
			case 4:
				System.out.println("Help");
				break;
		}
	}
}
